package com.action;

import com.bean.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.utils.CommonsUtils;
import com.utils.DrawActiveImg;
import com.utils.HibCommons;
import com.utils.MailUtils;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class UserAction extends ActionSupport {
	private User user = new User();

	/* About checkCode */
	private String checkCode;
	private ByteArrayInputStream inputStream;

	public String login() {
		/*
		 * login方法说明： 表单提交前，username、password、checkCode三个字段已经交由validation校验 其中
		 * username判断“是否为空”、“是否存在” password判断“是否为空” checkCode判断“是否为空”、“是否正确”
		 * 经过validation校验，程序才会到达这里 这里只校验password“是否正确”，以及用户激活码是否为“1”
		 * 即默认username不为空且存在，password不为空，checkCode不为空且正确
		 */

		/* 开启hibernate查询事务 */
		HibCommons.OpenQuery();

		User user_login = new User();
		user_login.setUsername(user.getUsername());
		user_login.setPassword(user.getPassword());

		String hql = "From User u where u.username = :username";
		try {
			Query query = HibCommons.getSession().createQuery(hql);
			query.setParameter("username", user_login.getUsername());
			List<User> list_user = query.list();

			HibCommons.CloseQuery();

			user_login.setImage(list_user.get(0).getImage());
			/* 校验密码是否正确 */
			if (list_user.get(0).getPassword().equals(user_login.getPassword())) {
				if (list_user.get(0).getLim().equals("1")) {
					ActionContext actionContext = ActionContext.getContext();
					Map map = actionContext.getSession();
					map.put("username", user_login);
					return SUCCESS;
				} else {
					this.addFieldError("user.password", "您还未激活，请查看邮箱并激活！");
					return INPUT;
				}
			} else {
				this.addFieldError("user.password", "密码错误!");
				return INPUT;
			}

		} catch (Exception e) {
			this.addFieldError("user.password", "密码错误!");
			return INPUT;
		}

	}

	public String checkCode() throws Exception {
		HttpServletResponse response = ServletActionContext.getResponse();

		// 设置浏览器不要缓存此图片
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);

		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ImageIO.write(DrawActiveImg.getImage(), "jpeg", outputStream);
		ByteArrayInputStream input = new ByteArrayInputStream(outputStream.toByteArray());
		this.setInputStream(input);

		HttpSession session = ServletActionContext.getRequest().getSession();
		session.setAttribute("checkCode", DrawActiveImg.getRands());
		input.close();
		outputStream.close();

		return SUCCESS;
	}

	public String regist() {
		/*
		 * regist方法说明： 表单提交前，username、password、phone、email四个字段已经交由validation校验
		 * 其中 username判断“是否为空”、“是否不存在” password判断“是否为空”、“是否符合正则表达式”
		 * phone判断“是否为空”、“是否符合正则表达式” email判断“是否为空”、“是否符合正则表达式”
		 * 经过validation校验，程序才会到达这里 这里不校验任何数据 即默认： username不为空且不存在
		 * password不为空且符合正则表达式 phone不为空且符合正则表达式 email不为空且符合正则表达式
		 */
		/* 开启hibernate查询事务 */
		HibCommons.OpenQuery();
		// 接收从表单获取的数据
		String username = user.getUsername();
		String password = user.getPassword();
		String email = user.getEmail();
		String activeCode = CommonsUtils.getUUID();
		String phone = user.getPhone();
		String lim = "0";
		String default_image = "logo.jpg";

		User user_regist = new User();
		user_regist.setUsername(username);
		user_regist.setPassword(password);
		user_regist.setPhone(phone);
		user_regist.setEmail(email);
		user_regist.setActiveCode(activeCode);
		user_regist.setLim(lim);
		user_regist.setImage(default_image);
		/* 将数据添加至数据库 */
		HibCommons.getSession().save(user_regist);

		/* 关闭hibernate查询 */
		HibCommons.CloseQuery();
		/* 注册成功后发送激活邮件 */
		String emailMsg = "恭喜您<b>"+ username +"</b>，您已注册成功，请点击下面的连接进行激活账户<br>" + "<a href='http://localhost:8080/WonderfulSong/active?activeCode="
				+ activeCode + "'>" + "http://localhost:8080/WonderfulSong/active?activeCode="+ activeCode +"</a><br><p>若不能直接跳转，请将链接复制到地址栏手动激活！</p>";
		try {
			MailUtils.sendActiveMail(email, emailMsg);
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

	public String logout() {
		/* 将session中的username对象移除 */
		ActionContext actionContext = ActionContext.getContext();
		Map map = actionContext.getSession();
		Object object = map.get("username");
		map.clear();
		return SUCCESS;
	}

	public String active() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String activeCode = request.getParameter("activeCode");

		HibCommons.OpenQuery();
		String hql = "UPDATE User u set u.lim = '1' WHERE u.activeCode = :activeCode";
		Query query = HibCommons.getSession().createQuery(hql);
		query.setParameter("activeCode", activeCode);
		query.executeUpdate();
		HibCommons.CloseQuery();
		return "success";
	}

	/* Getters & Setters */
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getCheckCode() {
		return checkCode;
	}

	public void setCheckCode(String checkCode) {
		this.checkCode = checkCode;
	}

	public ByteArrayInputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(ByteArrayInputStream inputStream) {
		this.inputStream = inputStream;
	}

}
